/* $RCSFile: Announcements.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Announcements/Announcements.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:18  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:45  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Settings;
using AddonNice.Diagnostics;
using AddonNice.Configuration.Settings;
using AddonNice.Settings.PageModules.Announcements;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.Announcements
{
    /// <summary>
    /// Initializer class for announcements 
    /// </summary>
    public class AnnouncementsSI : PortalCRMModuleControlSI
    {
        public AnnouncementsSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]AnnouncementsSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]AnnouncementsSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]AnnouncementsSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);
            
            string extgrp                           =   pm.ExtendedResourcesGroup;
            
			// Set Editor Settings 
			HtmlEditorDataType.AddEditorToSettings(bSettings, SettingItemGroup.MODULE_SPECIAL_SETTINGS,extgrp);


            SettingItemSpecial AllAnnouncements	    =	new SettingItemSpecial(AStr.AllAnnouncements,new BooleanDataType());
			AllAnnouncements.Value		            =	StStr.strFalse;        
			AllAnnouncements.Order		            =	1;	
			AllAnnouncements.ExtendedGroupName      =   extgrp;
            AllAnnouncements.Description		    =	"When set to true, read all the portal annoucements from DB.";
			AllAnnouncements.EnglishName		    =	"All Announcements";
			bSettings.AddSetting(AllAnnouncements);

            //Custom settings
            SettingItemSpecial DelayExpire		    =	new SettingItemSpecial(AStr.DelayExpire,new IntegerDataType());
            DelayExpire.Value			            =	"60";
            DelayExpire.Order		                =	10;	
			DelayExpire.MinValue		            =	0;
            DelayExpire.MaxValue		            =	3650; //10 years
			DelayExpire.ExtendedGroupName           =   extgrp;
            DelayExpire.Description		            =	"Expiration delay";
			DelayExpire.EnglishName		            =	"Expiration delay";
            bSettings.AddSetting(DelayExpire);

			SettingItemSpecial RepeatDirection      =	new SettingItemSpecial(AStr.RepeatDirectionSetting,new ListDataType("Vertical;Horizontal"));
			RepeatDirection.Required	            =	true;
			RepeatDirection.Value		            =	"Vertical";
            RepeatDirection.Order		            =	20;	
			RepeatDirection.ExtendedGroupName       =   extgrp;
            RepeatDirection.Description		        =	"Repeat Direction";
			RepeatDirection.EnglishName		        =	"Repeat Direction";
			bSettings.AddSetting(RepeatDirection);

			SettingItemSpecial RepeatColumn	        =	new SettingItemSpecial(AStr.RepeatColumns,new IntegerDataType());
			RepeatColumn.Required		            =	true;
			RepeatColumn.Value			            =	"1";
			RepeatColumn.MinValue		            =	1;
			RepeatColumn.MaxValue		            =	10;
			RepeatColumn.Order			            =	30;
			RepeatColumn.ExtendedGroupName          =   extgrp;
            RepeatColumn.Description		        =	"Columns number";
			RepeatColumn.EnglishName		        =	"Columns number";
			bSettings.AddSetting(RepeatColumn);

			SettingItemSpecial showItemBorder	    =	new SettingItemSpecial(AStr.ShowBorder,new BooleanDataType());
			showItemBorder.Value		            =	StStr.strFalse;        
			showItemBorder.Order			        =	40;
			showItemBorder.ExtendedGroupName        =   extgrp;
            showItemBorder.Description		        =	"Show Border";
			showItemBorder.EnglishName		        =	"Show Border";
			bSettings.AddSetting(showItemBorder);

			SettingItemSpecial setSortField         =   new SettingItemSpecial(AStr.SortField,new ListDataType("Title;CreatedDate;ExpireDate"));
			setSortField.ExtendedGroupName          =   extgrp;
            setSortField.Required                   =   true;
			setSortField.Value                      =   "ExpireDate";
			setSortField.Order			            =	50;
			setSortField.Description		        =	"Sort Field";
			setSortField.EnglishName		        =	"Sort Field";
			bSettings.AddSetting(setSortField);

			SettingItemSpecial setSortDirection     =   new SettingItemSpecial(AStr.SortDirection,new ListDataType("ASC;DESC"));
			setSortDirection.ExtendedGroupName      =    extgrp;
            setSortDirection.Required               =   true;
			setSortDirection.Value                  =   "DESC";
			setSortDirection.Order			        =	60;
			setSortDirection.Description		    =	"Sort Direction";
			setSortDirection.EnglishName		    =	"Sort Direction";
			bSettings.AddSetting(setSortDirection);
			
            SettingItemSpecial AddCRM	            =	new SettingItemSpecial(AStr.AddCRM,new BooleanDataType());
			AddCRM.Value		                    =	StStr.strFalse;        
			AddCRM.Order		                    =	70;	
			AddCRM.ExtendedGroupName                =   extgrp;
            AddCRM.Description		                =	"Mix CRM Announcements with normal announcements.";
			AddCRM.EnglishName		                =	"Add Crm";
			bSettings.AddSetting(AddCRM);

            SettingItemSpecial UseAnotherModuleID   =	new SettingItemSpecial(AStr.UseAnotherModuleID,new BooleanDataType());
			UseAnotherModuleID.Value		        =	StStr.strFalse;        
			UseAnotherModuleID.Order		        =	80;	
			UseAnotherModuleID.ExtendedGroupName    =   extgrp;
            UseAnotherModuleID.Description		    =	"Use another Module as source for DB Announcements announcements.";
			UseAnotherModuleID.EnglishName		    =	"Use another Module";
			bSettings.AddSetting(UseAnotherModuleID);

            SettingItemSpecial DedicatedModuleID	=	new SettingItemSpecial(AStr.DedicatedModuleID,new ModuleListDataType(Owner.ModuleID,new Guid[]{new Guid(StStr.AnnouncementsGuid),new Guid(StStr.AnnouncementRtGuid)}));
			DedicatedModuleID.Value		            =	"0";        
			DedicatedModuleID.Order		            =	90;	
			DedicatedModuleID.ExtendedGroupName     =   extgrp;
            DedicatedModuleID.Description		    =	"Select the module which will be source for annoucements.";
			DedicatedModuleID.EnglishName		    =	"Module to use as source";
			bSettings.AddSetting(DedicatedModuleID);

            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]AnnouncementsSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    /// <summary>
    /// Simple static announcements which could take items from db or from CRM only
    /// </summary>
    public partial class Announcements : PortalCRMModuleControl 
    {

        AnnouncementsDB announcements		=	new AnnouncementsDB();

		#region General Implementation

        public override Guid GuidID 
		{
			get
			{
				return new Guid(StStr.AnnouncementsGuid);
			}
		}

        /// <summary>
        /// General usage Module
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

        #endregion

        /// <summary>
        /// Public constructor. Sets base settings for module.
        /// </summary>
        public Announcements() 
        {}

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                     =   "ANNOUNCEMENTS";
                return extgrp;
            }
		}
 
        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new AnnouncementsSI(bSettings,this);
        }

        /// <summary>
        /// The Page_Load event handler on this User Control is used to
        /// obtain a DataSet of announcement information from the Announcements
        /// table, and then databind the results to a templated DataList
        /// server control.  It uses the AddonNice.AnnouncementsDB()
        /// data component to encapsulate all data functionality. 
        /// </summary>
        protected void Page_Load(object sender, System.EventArgs e) 
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Announcements Page_Load Time : {0}, LCID : {1}, DefLCID: {2}",DateTime.UtcNow,announcements.LCID,announcements.DefLCID),ModuleTraceSwitch.Sw.Info);
			if ( !IsPostBack )
            {
                myDataList.RepeatDirection			=	(Settings[AStr.RepeatDirectionSetting].ToString() == "Horizontal" ? 
                                                                                RepeatDirection.Horizontal : RepeatDirection.Vertical);
			    myDataList.RepeatColumns			=	Settings[AStr.RepeatColumns].ToInt();
			    string sortField					=	Settings[AStr.SortField].ToString();
			    string sortDirection				=	Settings[AStr.SortDirection].ToString();

			    if( Settings[AStr.ShowBorder].ToBool() )
			    {
				    myDataList.ItemStyle.BorderWidth=	Unit.Pixel(1);
			    }
			    // DataBind Announcements to DataList Control
			    try
			    {
                    int mid                 =   ModuleID;
                    bool AllAnnouncements   =   Settings[AStr.AllAnnouncements].ToBool();
                    if ( AllAnnouncements )
                    {
                        mid                 =   0;
				        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( "[V]Announcements Page_Load Import All.",ModuleTraceSwitch.Sw.Info);
                    }
                    DataTable tb            =   announcements.GetAnnouncementsGlobalized(mid);
                    if ( Settings[AStr.AddCRM].ToBool() )
                    {
				        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( "[V]Announcements Page_Load adding imports from Crm.",ModuleTraceSwitch.Sw.Info);
                        AnnouncementsUtil.AddFromCRM(Wrapper,ResetWrapper,tb);
                    }
                    if ( !AllAnnouncements && Settings[AStr.UseAnotherModuleID].ToBool() )
                    {
                        mid                 =   Settings[AStr.DedicatedModuleID].ToInt();
                        if ( mid != ModuleID )
                        {
				            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Announcements Page_Load adding imports from ModuleId: {0}",mid),ModuleTraceSwitch.Sw.Info);
                            DataTable tb2   =   announcements.GetAnnouncementsGlobalized(mid);
                            foreach( DataRow rx in tb2.Rows )
                                tb.ImportRow(rx);
                        }
                    }
				    DataView myDataView		=	tb.DefaultView;
				    myDataView.Sort			=	string.Format("{0} {1}",sortField,sortDirection);
				    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Announcements Page_Load Sort: {0}, Count: {1}",myDataView.Sort,myDataView.Count),ModuleTraceSwitch.Sw.Info);
				    myDataList.DataSource	=	myDataView;
				    myDataList.DataBind();

			    }
			    catch(Exception ex )
			    {
				    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Announcements Page_Load Time : {0}, ex : {1}",DateTime.UtcNow,ex),ModuleTraceSwitch.Sw.Info);
				    throw;
			    }
            }
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Announcements Page_Load END.",ModuleTraceSwitch.Sw.Info);
        }


        void myDataList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if ( e.Item.ItemType != ListItemType.Item &&
                e.Item.ItemType != ListItemType.AlternatingItem &&
                e.Item.ItemType != ListItemType.SelectedItem &&
                e.Item.ItemType != ListItemType.EditItem )
                return;
            HyperLink ctl   =  (HyperLink )e.Item.FindControl("moreLink");
            if ( ctl != null )
                ctl.CssClass    =   string.Format("AnnouncementsLink AnnouncementsLink_{0}",CurrentModulesLayout.Name);
            Label lb    =   (Label)e.Item.FindControl("LblTitle");
            if ( lb != null )
                lb.CssClass    =   string.Format("AnnouncementsTitle AnnouncementsTitle_{0}",CurrentModulesLayout.Name);
        }
 
        #region Std Overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
			AddUrl     =   Config.ModulesPath+"/Announcements/AnnouncementsEdit.aspx";
			AddText    =	"ADD";
            base.Page_PreInit(sender, e);
        }
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

        private void InitializeComponent() 
        {
			Load                        +=  new EventHandler(Page_Load);
            myDataList.ItemDataBound    +=  new DataListItemEventHandler(myDataList_ItemDataBound);
		}

		#endregion
    }
}

